//
//  RequestHandler.m
//  PigMarket
//
//  Created by Felix on 2019/4/11.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "RequestHandler.h"
#import "TokenCacheManager.h"
#import "NetworkManager.h"
#import "UIDevice+KeychainIDFV.h"
#import "SystemUtil.h"

@interface RequestHandler()

@property(nonatomic, strong) Request *request;

@property(nonatomic, copy) ResponseCallback callback;

@property (nonatomic, strong) NSURLSessionDataTask *task;

@property (nonatomic, assign) NSInteger repeatCount;

@end

@implementation RequestHandler

- (instancetype)initWithRequest: (Request *) request
               responseCallback: (ResponseCallback) callback {
    self = [super init];
    if (self) {
        self.request = request;
        self.callback = callback;
        self.repeatCount = 1;
    }
    return self;
}

- (void)sendRequest {
    
    
    NSString *accessToken = nil;
    __weak typeof(self) weakSelf = self;
    
    if (self.request.oauthType == OAuthTypeMember) { // 需要在http header携带member令牌
        
        Response *memberTokenResponse = [self getMemberToken];
        if (memberTokenResponse.code != ResultCodeSuccess) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.callback(memberTokenResponse);
            });
            
            return;
        }
        
        NSString *tokenInfo = memberTokenResponse.data;
        accessToken = tokenInfo;
        
        NSString *memberId = [NSString stringWithFormat:@"%@",[UserInfoDataProvider sharedInstance].userInfo.memberId];
        NSDictionary<NSString *,NSString *> *headers = @{@"token" : accessToken,
                                                         @"memberId" : memberId,
                                                         @"deviceNum" : [SystemUtil getUniqueId]
                                                         };
        
        NSLog(@"***************   %@", headers);
        self.request.headers = headers;
        
    }
    
    //发送请求
    self.task = [[NetworkManager sharedInstance] sendRequest:self.request completionHandler:^(Response *response) {
        
        
        if (weakSelf.request.oauthType == OAuthTypeMember) {//客户端鉴权
            
            if (response.code == ResultCodeLocalRequireLogin) {
                
                [[TokenCacheManager sharedInstance] clearMemberToken:accessToken];
                if (weakSelf.repeatCount > 0) {
                    weakSelf.repeatCount = weakSelf.repeatCount - 1;
                    
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
                        [weakSelf sendRequest];//递归
                    });
                    
                    return;
                }
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (weakSelf) {
                weakSelf.callback(response);
            }
        });
        
    }];
}

- (Response *)getMemberToken {
    NSString *memberToken = [TokenCacheManager sharedInstance].memberToken;
    
    if (memberToken && memberToken.length > 0) {
        
        Response *response = [[Response alloc] initWithCode:ResultCodeSuccess];
        response.data = memberToken;
        return response;
    }
    else {//
        Response *response = [Response responseWithCode:ResultCodeLocalRequireLogin msg:@"当前用户未登录"];
        return response;
    }
}

- (void)cancelRequest {
    if (self.task) {
        [self.task cancel];
    }
}
- (void)dealloc {
    NSLog(@"RequestHandler dealloc");
}

@end
